<template>
  <div class="analyse" v-loading="loading">
    <div class="top">
      <div class="search">
        <div class="contition">
          <div class="wrap_time">
            <date-time type="other" :query="timeQuery" @isFold="isShowFold"></date-time>
            <el-button type="primary" class="primary_btn fr find" @click.stop='search'>{{$t('public.search2')}}</el-button>
            <div class="clear"></div></div>
          <div class="wrap_drop">
            <unfold :isShow="isFold" :title="[]">
              <template slot="unfoldSlot">
                <div class="ask">
                  <span class="chan">{{$t('report.ConsulteChan')}}</span>
                  <el-select v-model="timeQuery.platform"
                             size="mini">
                    <el-option v-for="item in channels"
                               :label="item.label"
                               :value="item.value"
                               :key="item.value"></el-option></el-select>
                </div>
              </template>
            </unfold>
          </div>
        </div>
      </div>
      <affix :label="title"></affix>
    </div>
    <div :id = "id">
      <el-row class="ichars">
        <highcharts :options="highchartsOptions"></highcharts>
        <div class="notes">
          <span class="light">{{$t('report.hicharsNotes')}}: <span></span>{{$t('report.hicharsLight')}}</span>
          <span class="dark"><span></span>{{$t('report.hicharsDark')}}</span>
        </div>
      </el-row>
      <div class="tab">
        <div class="export">

          <!-- <el-button class="primary_btn fr report_excel_btn"
            v-if="$store.getters.exportFromEnd"
            @click.stop="exportXls"
          >{{$t('report.exportXls')+($store.state.xlsxExportMode==='Both'?'(旧)':'')}}</el-button> -->

          <el-button class="primary_btn fr report_excel_btn"
            @click.stop="exportXlsx"
          >{{$t('report.exportXls')}}</el-button>

          <el-button class="primary_btn fr pdf" @click.stop="exportPdf">{{$t('report.exportPDF')}}</el-button>
        </div>
        <div class="deploy">
          <el-collapse accordion>
            <el-collapse-item>
              <template slot="title">
                <span class="fl explain">{{$t('report.toggleInstructe')}}</span>
              </template>
              <div>
                {{$t('report.robotConverNum')}}<br/>
                {{$t('report.tipAnswerRightRate')}}<br/>
                {{$t('report.robotAnswerNum')}}<br/>
                {{$t('report.robotGreetAnsNUm')}}<br/>
                {{$t('report.robotBusAnsNum')}}<br/>
                {{$t('report.robotBusGuideNum')}}<br/>
                {{$t('report.robotNotAnsNum')}}
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
        <report-table :data="tableData" :config="headOptions"></report-table>
      </div>
    </div>
    <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :title="$t('report.reportExportHelp')" :visible.sync="dialogVisible" width="30%">
      <span>{{$t('report.reportExportTipTitle')}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button class="primary_btn" @click="dialogVisible = false">{{$t('public.cancel')}}</el-button>
        <el-button class="primary_btn" type="primary" @click="confirm">{{$t('public.confirm')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import affix from '../../../ui-modules/affix/Affix.vue'
  import unfold from '../../../ui-modules/unfold/index.vue'
  import dateTime from '../base/datetime.vue'
  import reportTable from '../base/reportTable.vue'
  import { deepClone } from '@/utils/m7Utils.js'
  import { exportReportPdf, headOptionsToXlsxHeaders, searchTime, colorConfigArr, checkTime } from '@/utils/reportUtils.js'
  import * as XlsxUtil from 'src/utils/XlsxUtil.umd.js'
  export default {
    name: 'robot_report_message',
    data () {
      return {
        isFold: false,
        loading: false,
        id: 'robot_report_message',
        title: this.$t('report.robotReportMessage'),
        timeQuery: {platform: ''},
        dialogVisible: false,
        serverData: [],
        channels: [{
          label: this.$t('public.all'),
          value: ''
        }, {
          label: this.$t('report.imPlatform.pc'),
          value: 'pc'
        }, {
          label: this.$t('report.imPlatform.wap'),
          value: 'wap'
        }, {
          label: this.$t('report.imPlatform.sdk'),
          value: 'sdk'
        }, {
          label: this.$t('report.imPlatform.weixin'),
          value: 'weixin'
        }, {
          label: this.$t('report.imPlatform.wxmini'),
          value: 'wxmini'
        }, {
          label: this.$t('report.imPlatform.weibo'),
          value: 'weibo'
        }, {
          label: this.$t('report.imPlatform.enterprise'),
          value: 'wxEnterprise'
        }, {
          label: this.$t('report.imPlatform.baiduBCP'),
          value: 'ocpc'
        }, {
          label: this.$t('report.imPlatform.tikTok'),
          value: 'dy'
        }, {
          label: this.$t('report.imPlatform.wxkf'),
          value: 'wxkf'
        }],
        headOptions: [{
          'order': '1',
          'name': 'time',
          'displayname': this.$t('public.time'),
          'show': true
        }, {
          'order': '2',
          'name': 'sessionCount',
          'displayname': this.$t('report.numberConversations'),
          'show': true
        }, {
          'order': '3',
          'name': 'answerRightRate',
          'displayname': this.$t('report.answerRightRate'),
          'show': true
        }, {
          'order': '4',
          'name': 'answerCount',
          'displayname': this.$t('report.answerTotal'),
          'show': true
        }, {
          'order': '5',
          'name': 'commonCount',
          'displayname': this.$t('report.greetAnswerNumber'),
          'show': true
        }, {
          'order': '6',
          'name': 'businessCount',
          'displayname': this.$t('report.businessResponsesNum'),
          'show': true
        }, {
          'order': '7',
          'name': 'businessLeadsCount',
          'displayname': this.$t('report.businessLeadsResponsesNum'),
          'show': true
        }, {
          'order': '8',
          'name': 'usefulCount',
          'displayname': this.$t('report.haveHelp'),
          'show': true
        }, {
          'order': '9',
          'name': 'uselessCount',
          'displayname': this.$t('report.noHelp'),
          'show': true
        }, {
          'order': '10',
          'name': 'unknownCount',
          'displayname': this.$t('report.unknownResponsesNum'),
          'show': true
        }],
        highchartsDefaultOptions: {
          chart: { type: '', animation: false },
          colors: colorConfigArr,
          xAxis: {
            categories: [],
            title: {
              enabled: true,
              text: '',
              style: { fontWeight: 'normal' }
            }
          },
          yAxis: {
            gridLineColor: '#e6e6e6',
            allowDecimals: false,
            title: { text: '' },
            showEmpty: false
          },
          title: { text: this.$t('report.robotReportMessage') },
          legend: { align: 'center', verticalAlign: 'top', y: 30 },
          tooltip: {
            pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}{point.valueSuffix}</b><br/>',
            shared: true
          },
          credits: { enabled: false },
          series: []
        }
      }
    },
    components: {
      affix,
      unfold,
      dateTime,
      reportTable
    },
    computed: {
      tableData () {
        return this.getTableData(this.serverData)
      },
      highchartsOptions () {
        let options = deepClone(this.highchartsDefaultOptions)
        if (!this.serverData || this.serverData.length === 0) {
          return options
        }

        let headerConfig = this.headOptions
        let datas = this.serverData
        let categoriesArray = []
        let seriesArray = []

        headerConfig.forEach(item => {
          if (!item.show) {
            return
          }
          if (item.name === 'time') {
            return
          }
          let serie = { name: item.displayname, data: [], valueName: item.name }
          if (item.name === 'answerRightRate') {
            serie.tooltip = { valueSuffix: '%' }
          }
          seriesArray.push(serie)
        })

        for (let i = 0; i < datas.length; i++) {
          categoriesArray.push(datas[i].time)
          for (let j = 0; j < seriesArray.length; j++) {
            seriesArray[j].data.push(parseFloat(datas[i][seriesArray[j].valueName]))
          }
        }

        options.xAxis.categories = categoriesArray
        options.series = seriesArray

        return options
      }
    },
    methods: {
      isShowFold (bool) {
        this.isFold = bool
      },
      getTableData (serverData) {
        if (!serverData || serverData.length === 0) {
          return []
        }
        let data = deepClone(serverData)
        return data
      },
      getSearchQueryData () {
        let start = this.timeQuery.StartTime ? this.timeQuery.StartTime.replace(/-/g, '').replace(/:/g, '').replace(/\s/g, '') : 0
        let end = this.timeQuery.EndTime ? this.timeQuery.EndTime.replace(/-/g, '').replace(/:/g, '').replace(/\s/g, '') : 0
        if (start && end) {
          if (parseInt(end) < parseInt(start)) {
            this.$message.error(this.$t('report.queryTimeErr'))
            return
          }
        }
        let data = {
          reportType: this.id,
          account: this.$store.state.session.user.account,
          query: { reportType: this.id }
        }
        let query = deepClone(this.timeQuery)
        if (query.timeType === 'other') {
          // 校验类型与时间
          let message = checkTime(query.StartTime, query.EndTime, false, true)
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        data.query = Object.assign({}, data.query, query)
        if (this.timeQuery.platform) {
          data.query.platform = this.timeQuery.platform
        } else {
          delete data.query.platform
        }
        return data
      },
      search () {
        var data = this.getSearchQueryData()
        if (!data) {
          return
        }
        this.loading = true
        this.$store.dispatch('queryRobotMessageReport', data).then((res) => {
          // 表头
          this.serverData = deepClone(res.data)
          this.loading = false
        })
      },
      exportXlsx () {
        var data = this.getSearchQueryData()
        if (!data) {
          return
        }
        this.loading = true
        this.$store.dispatch('queryRobotMessageReport', data).then((res) => {
          this.loading = false
          var serverData = deepClone(res.data)
          var headOptions = deepClone(this.headOptions)

          var tableData = this.getTableData(serverData)
          var headers = headOptionsToXlsxHeaders(headOptions)

          var dh = XlsxUtil.getDownloadHelper(headers, tableData)
          var timeStamp = XlsxUtil.dateFormat(new Date(), 'yyyy-MM-dd hh-mm-ss')
          dh.download(this.$t('report.robotReportMessage') + timeStamp)
        })
      },
      exportXls () {
        let data = {
          Method: 'exportRobotMessageExcel',
          Query: {reportType: this.id, accountId: this.$store.state.session.user.account}
        }
        let query = deepClone(this.timeQuery)
        if (query.timeType === 'other') {
          // 校验类型与时间
          let message = checkTime(query.StartTime, query.EndTime, false, true)
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        data.Query = Object.assign({}, data.Query, query)
        if (this.timeQuery.platform) {
          data.Query.platform = this.timeQuery.platform
        } else {
          delete data.Query.platform
        }
        this.$store.dispatch('exportRobotMessageExcel', data)
      },
      exportPdf () {
        this.dialogVisible = true
      },
      confirm () {
        this.dialogVisible = false
        exportReportPdf({title: this.$t('report.robotReportMessage') + searchTime(this.timeQuery), id: this.id})
      }
    },
    beforeMount () {
      this.$nextTick(function () {
        this.search()
      })
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  .analyse
    .export
      .pdf
        margin 0px
    .search
      .ask
        margin-top 14px
        .chan
          margin-right 8px
    .deploy
      .tex
      .te
        cursor pointer
      .set
        margin-right 10px
        position relative
        top 2px
      .tip
        margin-left 0
</style>
